import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
// import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')

  // 添加环境变量调试日志
  console.log('当前环境变量:', {
    mode,
    VITE_API_BASE_URL: env.VITE_API_BASE_URL,
  })

  return {
    plugins: [vue()],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      proxy: {
        '/api': {
          target: env.VITE_API_BASE_URL || 'http://117.72.105.56:8090', // 默认生产环境
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
    build: {
      // 优化构建设置
      minify: 'terser',
      terserOptions: {
        compress: {
          // 避免某些情况下的压缩问题
          drop_console: mode === 'production',
          drop_debugger: mode === 'production',
        },
      },
      // 分割代码块
      rollupOptions: {
        output: {
          manualChunks: {
            'three-vendor': ['three'],
            'vue-vendor': ['vue', 'vue-router', 'pinia'],
            'ant-vendor': ['ant-design-vue'],
          },
        },
      },
    },
  }
})
